home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / plugin.py < prev    next >
Encoding:
Python Source  |  2009-04-14  |  12.9 KB  |  399 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  19. #
  20. # Author: Don Welch
  21. #
  22.  
  23. __version__ = '2.1'
  24. __mod__ = 'hp-plugin'
  25. __title__ = 'Plugin Download and Install Utility'
  26. __doc__ = ""
  27.  
  28. # Std Lib
  29. import sys
  30. import getopt
  31. import time
  32. import os.path
  33. import re
  34. import os
  35. import gzip
  36.  
  37. # Local
  38. from base.g import *
  39. from base import device, utils, tui, module
  40. from prnt import cups
  41.  
  42. pm = None
  43.  
  44. def plugin_download_callback(c, s, t):
  45.     pm.update(int(100*c*s/t),
  46.              utils.format_bytes(c*s))
  47.  
  48.  
  49. def plugin_install_callback(s):
  50.     print s
  51.  
  52.  
  53.  
  54. USAGE = [ (__doc__, "", "name", True),
  55.           ("Usage: %s [MODE] [OPTIONS]" % __mod__, "", "summary", True),
  56.           utils.USAGE_MODE,
  57.           utils.USAGE_GUI_MODE,
  58.           utils.USAGE_INTERACTIVE_MODE,
  59.           ("Installation for required printer mode:", "--required (Qt4 only)", "option", False),
  60.           ("Installation for optional printer mode:", "--optional (Qt4 only)", "option", False),
  61.           #("Installation generic mode:", "--generic (default)", "option", False),
  62.           utils.USAGE_LANGUAGE,
  63.           utils.USAGE_OPTIONS,
  64.           ("Specify the path to the plugin file:", "-p <path> or --path=<path> or --plugin=<path>", "option", False),
  65.           utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
  66.           utils.USAGE_HELP,
  67.           utils.USAGE_SPACE,
  68.           utils.USAGE_SEEALSO,
  69.           ("hp-setup", "", "seealso", False),
  70.           ("hp-firmware", "", "seealso", False),
  71.         ]
  72.  
  73.  
  74. mod = module.Module(__mod__, __title__, __version__, __doc__, USAGE,
  75.                     (INTERACTIVE_MODE, GUI_MODE),
  76.                     (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4), True)
  77.  
  78. opts, device_uri, printer_name, mode, ui_toolkit, loc = \
  79.     mod.parseStdOpts('p:', ['path=', 'plugin=', 'plug-in=',
  80.                             'generic', 'optional', 'required'],
  81.                      handle_device_printer=False)
  82.  
  83. plugin_path = None
  84. install_mode = PLUGIN_NONE # reuse plugin types for mode (PLUGIN_NONE = generic)
  85.  
  86. for o, a in opts:
  87.     if o in ('-p', '--path', '--plugin', '--plug-in'):
  88.         plugin_path = os.path.normpath(os.path.abspath(os.path.expanduser(a)))
  89.  
  90.     elif o == '--required':
  91.         install_mode = PLUGIN_REQUIRED
  92.         if ui_toolkit == 'qt3':
  93.             log.warn("--required switch ignored.")
  94.  
  95.     elif o == '--optional':
  96.         install_mode = PLUGIN_OPTIONAL
  97.         if ui_toolkit == 'qt3':
  98.             log.warn("--optional switch ignored.")
  99.  
  100.  
  101. version = prop.installed_version
  102. plugin_filename = 'hplip-%s-plugin.run' % version
  103.  
  104. if plugin_path is not None:
  105.     if not os.path.exists(plugin_path):
  106.         log.error("Plug-in path '%s' not found." % plugin_path)
  107.         sys.exit(1)
  108.  
  109.     if os.path.isdir(plugin_path):
  110.         plugin_path = os.path.join(plugin_path, 'hplip-%s-plugin.run' % version)
  111.  
  112.         if not os.path.exists(plugin_path):
  113.             log.error("Plug-in path '%s' not found." % plugin_path)
  114.             sys.exit(1)
  115.  
  116.     if os.path.basename(plugin_path) != plugin_filename:
  117.         log.error("Plug-in filename must be '%s'." % plugin_filename)
  118.         sys.exit(1)
  119.  
  120.  
  121.     size, checksum, timestamp = os.stat(plugin_path)[6], '', 0.0
  122.     plugin_path = 'file://' + plugin_path
  123.     log.debug("Plugin path=%s (%d)" % (plugin_path, size))
  124.  
  125.  
  126. if mode == GUI_MODE:
  127.     if ui_toolkit == 'qt3':
  128.         if not utils.canEnterGUIMode():
  129.             log.error("%s requires GUI support (try running with --qt4). Try using interactive (-i) mode." % __mod__)
  130.             sys.exit(1)
  131.     else:
  132.         if not utils.canEnterGUIMode4():
  133.             log.error("%s requires GUI support (try running with --qt3). Try using interactive (-i) mode." % __mod__)
  134.             sys.exit(1)
  135.  
  136.  
  137. if mode == GUI_MODE:
  138.     if ui_toolkit == 'qt3':
  139.         try:
  140.             from qt import *
  141.             from ui import pluginform2
  142.         except ImportError:
  143.             log.error("Unable to load Qt3 support. Is it installed?")
  144.             sys.exit(1)
  145.  
  146.         app = QApplication(sys.argv)
  147.         QObject.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
  148.  
  149.         if loc is None:
  150.             loc = user_conf.get('ui', 'loc', 'system')
  151.             if loc.lower() == 'system':
  152.                 loc = str(QTextCodec.locale())
  153.                 log.debug("Using system locale: %s" % loc)
  154.  
  155.         if loc.lower() != 'c':
  156.             e = 'utf8'
  157.             try:
  158.                 l, x = loc.split('.')
  159.                 loc = '.'.join([l, e])
  160.             except ValueError:
  161.                 l = loc
  162.                 loc = '.'.join([loc, e])
  163.  
  164.             log.debug("Trying to load .qm file for %s locale." % loc)
  165.             trans = QTranslator(None)
  166.  
  167.             qm_file = 'hplip_%s.qm' % l
  168.             log.debug("Name of .qm file: %s" % qm_file)
  169.             loaded = trans.load(qm_file, prop.localization_dir)
  170.  
  171.             if loaded:
  172.                 app.installTranslator(trans)
  173.             else:
  174.                 loc = 'c'
  175.  
  176.         if loc == 'c':
  177.             log.debug("Using default 'C' locale")
  178.         else:
  179.             log.debug("Using locale: %s" % loc)
  180.             QLocale.setDefault(QLocale(loc))
  181.             prop.locale = loc
  182.             try:
  183.                 locale.setlocale(locale.LC_ALL, locale.normalize(loc))
  184.             except locale.Error:
  185.                 pass
  186.  
  187.         if not os.geteuid() == 0:
  188.             log.error("You must be root to run this utility.")
  189.  
  190.             QMessageBox.critical(None,
  191.                                  "HP Device Manager - Plug-in Installer",
  192.                                  "You must be root to run hp-plugin.",
  193.                                   QMessageBox.Ok,
  194.                                   QMessageBox.NoButton,
  195.                                   QMessageBox.NoButton)
  196.  
  197.             sys.exit(1)
  198.  
  199.         w = pluginform2.PluginForm2()
  200.         app.setMainWidget(w)
  201.         w.show()
  202.  
  203.         app.exec_loop()
  204.  
  205.     else: # qt4
  206.         try:
  207.             from PyQt4.QtGui import QApplication, QMessageBox
  208.             from ui4.plugindialog import PluginDialog
  209.         except ImportError:
  210.             log.error("Unable to load Qt4 support. Is it installed?")
  211.             sys.exit(1)
  212.  
  213.         app = QApplication(sys.argv)
  214.  
  215.         if not os.geteuid() == 0:
  216.             log.error("You must be root to run this utility.")
  217.  
  218.             QMessageBox.critical(None,
  219.                                  "HP Device Manager - Plug-in Installer",
  220.                                  "You must be root to run hp-plugin.",
  221.                                   QMessageBox.Ok,
  222.                                   QMessageBox.NoButton,
  223.                                   QMessageBox.NoButton)
  224.  
  225.             sys.exit(1)
  226.  
  227.  
  228.         dialog = PluginDialog(None, install_mode)
  229.         dialog.show()
  230.         try:
  231.             log.debug("Starting GUI loop...")
  232.             app.exec_()
  233.         except KeyboardInterrupt:
  234.             log.error("User exit")
  235.             sys.exit(0)
  236.  
  237.  
  238. else: # INTERACTIVE_MODE
  239.     try:
  240.         if not os.geteuid() == 0:
  241.             log.error("You must be root to run this utility.")
  242.             sys.exit(1)
  243.  
  244.         log.info("(Note: Defaults for each question are maked with a '*'. Press <enter> to accept the default.)")
  245.         log.info("")
  246.  
  247.         from installer import core_install
  248.         core = core_install.CoreInstall()
  249.  
  250.         core.set_plugin_version()
  251.  
  252.         tui.header("PLUG-IN INSTALLATION FOR HPLIP %s" % version)
  253.  
  254.         if core.check_for_plugin() and plugin_path is None:
  255.             log.info("The driver plugin for HPLIP %s appears to already be installed." % version)
  256.  
  257.             cont, ans = tui.enter_yes_no("Do you wish to download and re-install the plug-in?")
  258.  
  259.             if not cont or not ans:
  260.                 sys.exit(0)
  261.  
  262.  
  263.         if plugin_path is None:
  264.             table = tui.Formatter(header=('Option', 'Description'), min_widths=(10, 50))
  265.             table.add(('d', 'Download plug-in from HP (recomended)'))
  266.             table.add(('p', 'Specify a path to the plug-in (advanced)'))
  267.             table.add(('q', 'Quit hp-plugin (skip installation)'))
  268.  
  269.             table.output()
  270.  
  271.             cont, ans = tui.enter_choice("\nEnter option (d=download*, p=specify path, q=quit) ? ",
  272.                 ['d', 'p'], 'd')
  273.  
  274.             if not cont: # q
  275.                 sys.exit(0)
  276.  
  277.  
  278.             if ans == 'd': # d - download
  279.                 # read plugin.conf (local or on sf.net) to get plugin_path (http://)
  280.                 plugin_conf_url = core.get_plugin_conf_url()
  281.  
  282.                 if plugin_conf_url.startswith('file://'):
  283.                     tui.header("COPY CONFIGURATION")
  284.                 else:
  285.                     tui.header("DOWNLOAD CONFIGURATION")
  286.  
  287.                     log.info("Checking for network connection...")
  288.                     ok = core.check_network_connection()
  289.  
  290.                     if not ok:
  291.                         log.error("Network connection not detected.")
  292.                         sys.exit(1)
  293.  
  294.  
  295.                 log.info("Downloading configuration file from: %s" % plugin_conf_url)
  296.                 pm = tui.ProgressMeter("Downloading configuration:")
  297.  
  298.                 plugin_path, size, checksum, timestamp, ok = core.get_plugin_info(plugin_conf_url,
  299.                     plugin_download_callback)
  300.  
  301.                 print
  302.  
  303.                 if not plugin_path.startswith('http://') and not plugin_path.startswith('file://'):
  304.                     plugin_path = 'file://' + plugin_path
  305.  
  306.             else: # p - specify plugin path
  307.  
  308.                 while True:
  309.                     plugin_path = raw_input(log.bold("Enter the path to the 'hplip-%s-plugin.run' file (q=quit) : " %
  310.                         version)).strip()
  311.  
  312.                     if plugin_path.strip().lower() == 'q':
  313.                         sys.exit(1)
  314.  
  315.                     if not plugin_path.startswith('http://'):
  316.                         plugin_path = os.path.normpath(os.path.abspath(os.path.expanduser(plugin_path)))
  317.  
  318.                         if not os.path.exists(plugin_path):
  319.                             log.error("Plug-in path '%s' not found." % plugin_path)
  320.                             continue
  321.  
  322.                         if os.path.isdir(plugin_path):
  323.                             plugin_path = os.path.join(plugin_path, plugin_filename)
  324.  
  325.                             if not os.path.exists(plugin_path):
  326.                                 log.error("Plug-in path '%s' not found." % plugin_path)
  327.                                 continue
  328.  
  329.                         if os.path.basename(plugin_path) != plugin_filename:
  330.                             log.error("Plug-in filename must be '%s'." % plugin_filename)
  331.                             continue
  332.  
  333.                         size, checksum, timestamp = os.stat(plugin_path)[6], '', 0.0
  334.                         plugin_path = 'file://' + plugin_path
  335.  
  336.                     break
  337.  
  338.  
  339.         if plugin_path.startswith('file://'):
  340.             tui.header("COPY PLUGIN")
  341.         else:
  342.             tui.header("DOWNLOAD PLUGIN")
  343.  
  344.             log.info("Checking for network connection...")
  345.             ok = core.check_network_connection()
  346.  
  347.             if not ok:
  348.                 log.error("Network connection not detected.")
  349.                 sys.exit(1)
  350.  
  351.         log.info("Downloading plug-in from: %s" % plugin_path)
  352.         pm = tui.ProgressMeter("Downloading plug-in:")
  353.  
  354.         ok, local_plugin = core.download_plugin(plugin_path, size, checksum, timestamp, plugin_download_callback)
  355.         print
  356.  
  357.         if not ok:
  358.             log.error("Plug-in download failed: %s" % local_plugin)
  359.             sys.exit(1)
  360.  
  361.         tui.header("INSTALLING PLUG-IN")
  362.  
  363.         core.run_plugin(mode, plugin_install_callback)
  364.  
  365.         cups_devices = device.getSupportedCUPSDevices(['hp']) #, 'hpfax'])
  366.         #print cups_devices
  367.  
  368.         title = False
  369.  
  370.         for dev in cups_devices:
  371.             mq = device.queryModelByURI(dev)
  372.  
  373.             if mq.get('fw-download', 0):
  374.  
  375.                 if not title:
  376.                     tui.header("DOWNLOADING FIRMWARE")
  377.                     title = True
  378.  
  379.                 # Download firmware if needed
  380.                 log.info(log.bold("\nDownloading firmware to device %s..." % dev))
  381.                 try:
  382.                     d = device.Device(dev)
  383.                 except Error:
  384.                     log.error("Error opening device. Exiting.")
  385.                     sys.exit(1)
  386.  
  387.                 if d.downloadFirmware():
  388.                     log.info("Firmware download successful.\n")
  389.  
  390.                 d.close()
  391.  
  392.  
  393.     except KeyboardInterrupt:
  394.         log.error("User exit")
  395.  
  396. log.info("")
  397. log.info("Done.")
  398.  
  399.